/**
 * Copyright (c) www.bugull.com
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ebocy.hammer.core.db.mongo;

import com.ebocy.hammer.core.db.IConnection;
import com.ebocy.hammer.core.db.mongo.mapper.CascadeDeleteExecutor;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoOptions;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import org.apache.log4j.Logger;

/**
 * The connection to MongoDB.
 *
 * <p>
 * Singleton Pattern is used here. An application should use only one
 * BuguConnection.
 * </p>
 *
 * @author Frank Wen(xbwen@hotmail.com)
 */
public class MongoConnection implements IConnection{

	private final static Logger logger = Logger
			.getLogger(MongoConnection.class);

	private static MongoConnection instance = new MongoConnection();

	private String host;
	private int port;
	private List<ServerAddress> replicaSet;
	private ReadPreference readPreference;
	private MongoOptions options;
	private String database;
	private String username;
	private String password;
	private Mongo mongo;
	private DB db;
	public boolean isAuth() {
		return isAuth;
	}

	public void setAuth(boolean isAuth) {
		this.isAuth = isAuth;
	}

	private boolean isAuth=true;

	private MongoConnection() {

	}

	public static MongoConnection getInstance() {
		return instance;
	}

	public void connect(String host, int port, String database) {
		this.host = host;
		this.port = port;
		this.database = database;
		connect();
	}

	public void connect(String host, int port, String database,
			String username, String password) {
		this.host = host;
		this.port = port;
		this.database = database;
		this.username = username;
		this.password = password;
		connect();
	}

	public void connect(List<ServerAddress> replicaSet, String database,
			String username, String password) {
		this.replicaSet = replicaSet;
		this.database = database;
		this.username = username;
		this.password = password;
		connect();
	}

	public boolean connect() {
		boolean isok = doConnect();
		if (isAuth) {
			isok = auth();
		}
		return isok;
	}

	private boolean doConnect() {
		try {
			if (host != null && port != 0) {
				ServerAddress sa = new ServerAddress(host, port);
				if (options != null) {
					mongo = new Mongo(sa, options);
				} else {
					mongo = new Mongo(sa);
				}
			} else if (replicaSet != null) {
				if (options != null) {
					mongo = new Mongo(replicaSet, options);
				} else {
					mongo = new Mongo(replicaSet);
				}
				if (readPreference != null) {
					mongo.setReadPreference(readPreference);
				}
			}
		} catch (UnknownHostException ex) {
			logger.error("Can not connect to the MongoDB host", ex);
		}
		if (mongo == null) {
			logger.error("Can not connect to mongoDB.");
			return false;
		}
		db = mongo.getDB(database);
		return true;
	}

	public boolean close() {
		try {
			ExecutorService executor = CascadeDeleteExecutor.getInstance()
					.getExecutor();
			if (executor != null) {
				executor.shutdown();
			}
			if (mongo != null) {
				mongo.close();
			}
			return true;
		} catch (Exception e) {
			logger.error("close db connection is failed!", e);
			return false;
		}

	}

	private boolean auth() {
		boolean auth = db.authenticate(username, password.toCharArray());
		if (auth) {
			logger.info("Connected to mongodb successfully!");
			return true;
		} else {
			db = null;
			logger.error("Can not connect to mongodb. Failed to authenticate!");
			return false;
		}
	}

	public MongoConnection setHost(String host) {
		this.host = host;
		return this;
	}

	public MongoConnection setPort(int port) {
		this.port = port;
		return this;
	}

	public MongoConnection setDatabase(String database) {
		this.database = database;
		return this;
	}

	public MongoConnection setUsername(String username) {
		this.username = username;
		return this;
	}

	public MongoConnection setPassword(String password) {
		this.password = password;
		return this;
	}

	public MongoConnection setOptions(MongoOptions options) {
		this.options = options;
		return this;
	}

	public MongoConnection setReplicaSet(List<ServerAddress> replicaSet) {
		this.replicaSet = replicaSet;
		return this;
	}

	public MongoConnection setReadPreference(ReadPreference readPreference) {
		this.readPreference = readPreference;
		return this;
	}

	public DB getDB() {
		return db;
	}
}
